using System;
using System.Collections.Generic;
using UnityEngine;
using ZSW.Framework.Utils;

namespace ZSW.Framework
{

    public class ZSWF_MainThreadHandler : ZSWF_Singleton<ZSWF_MainThreadHandler>
    {
        // 队列数量
        public int QueueCount => actionQueue.Count;

        // 待处理的Action队列
        private Queue<System.Action> actionQueue = new Queue<System.Action>();

        // 1次Update最大处理的Action数量
        [SerializeField] private int maxActionCountPerUpdate = 20;

        // 1次Update最大处理时间，超过则等待下次Update处理（单位：毫秒）
        [SerializeField] private long maxActionTimePerUpdate = 5;

        private void Update()
        {
            long startTime = ZSWFUtil_Date.CurrentMillisecondsTimestamp();
            long useTime = 0;
            if (actionQueue.Count > 0)
            {
                int count = 0;
                while (actionQueue.Count > 0 &&
                    count < maxActionCountPerUpdate &&
                    useTime < maxActionTimePerUpdate)
                {
                    System.Action action = actionQueue.Dequeue();
                    action();
                    useTime = ZSWFUtil_Date.CurrentMillisecondsTimestamp() - startTime;
                    count++;
                }
            }
        }

        /// <summary>
        /// 执行方法
        /// </summary>
        /// <param name="action"></param>
        /// <param name="immediately"></param>
        public void TakeAction(Action action, bool immediately = false)
        {
            if (immediately)
            {
                action();
            }
            else
            {
                actionQueue.Enqueue(action);
            }
        }

        /// <summary>
        /// 立即执行方法
        /// </summary>
        /// <param name="action"></param>
        public void TakeActionImmediately(Action action)
        {
            action();
        }
    }
}